package com.itzjc.utils;

import com.itzjc.domain.pojo.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * TODO
 *
 * @className: JWTUtils
 * @date: 2021-06-04 15:55
 **/
public class JWTUtils {
    /**
     * 过期时间
     **/
    private static final long EXPIRE = 6000 * 60 * 24 * 7;

    /**
     * 加密秘钥
     **/
    private static final String SECRET = "zjcIt.secret";

    /**
     * 令牌前缀
     **/
    private static final String TOKEN_PRFIX = "zjcIt";

    /**
     * 颁布者
     **/
    private static final String SUBJECT = "jcmster";

    /**
     * 根据用户信息，生成令牌
     *
     * @param user
     * @return:
     **/
    public static String geneJsonWebToken(User user) {

        String token = Jwts.builder().setSubject(SUBJECT)
                .claim("head_img", user.getHeadImg())
                .claim("id", user.getId())
                .claim("name", user.getUserName())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, SECRET).compact();
        token = TOKEN_PRFIX + token;

        return token;
    }

    /**
     * 验证TOKEN
     *
     * @param token
     * @return:
     **/
    public static Claims checkJWT(String token) {
        try {
            final Claims claims = Jwts.parser().setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PRFIX, ""))
                    .getBody();
            return claims;
        } catch (Exception e) {
            return null;
        }
    }

}
